# -*- coding:utf-8 -*-
import time

from pynput.keyboard import Key, Listener

from common.data import DB


def press_key(key):
    # 当前按下的时间
    pressTime = time.time()
    DB.pressTime = pressTime

    try:
        beforeKeyPressTime = DB.beforeKeyPressed[f"{key}"]["pressTime"]
        # 点击时间差
        time_difference = pressTime - beforeKeyPressTime
    except KeyError:
        # 第一次启动时，没有该字段时，默认时间差0.5秒
        time_difference = 0.5

    DB.beforeKeyPressed[f"{key}"] = {"pressTime": time.time(), "sleepTime": time_difference}


def release_key(key):
    pressedTime = time.time()
    pressTime = DB.beforeKeyPressed[f"{key}"]["pressTime"]
    sleepTime = DB.beforeKeyPressed[f"{key}"]["sleepTime"]
    duration = pressedTime - pressTime
    press_action = {
        "type": "keyboard", "action": "KeyPress", "key": f"{key}", "sleepTime": sleepTime, "duration": duration
    }
    DB.caseData["cases"].append(press_action)

    # if key == Key.esc:
    #     raise Listener.StopException("停止")
